package com.parleys.android.client.io;

import java.util.ArrayList;
import java.util.HashSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.util.Log;

import com.parleys.android.client.provider.ParleysContract;
import com.parleys.android.client.provider.ParleysContract.Channels;
import com.parleys.android.client.provider.ParleysContract.Presentations;
import com.parleys.android.client.util.ParleysUriUtils;
import com.parleys.android.client.util.Sets;

public class PresentationsHandler extends JSONHandler {
	
	private static final String TAG = "PresentationsHandler";
	
	public PresentationsHandler() {
		super(ParleysContract.CONTENT_AUTHORITY);
	}

	@Override
	public ArrayList<ContentProviderOperation> parse(JSONArray json, ContentResolver resolver) throws JSONException {
		final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
		final HashSet<Long> presentationIds = Sets.newHashSet();
		
		final int jsonSize = json.length();
		for (int i = 0; i < jsonSize; i++) {
			final JSONObject presentation = json.getJSONObject(i);
			final long presentationId = presentation.getLong("id");
			final int channelId = presentation.getInt("channelId");
			final long createdOn = presentation.getLong("createdOn");
			final long modifiedOn = presentation.getLong("modifiedOn");
			final String title = presentation.getString("title");
			final String summary = presentation.getString("summary");
			final String thumbnailUrl = ParleysUriUtils.removeLeadingSlashes(presentation.getString("thumbnailUrl"));
			final String mp3Url = ParleysUriUtils.removeLeadingSlashes(presentation.getString("mp3Url"));
			final boolean visibleIpad = presentation.getBoolean("visibleIpad");
			final boolean iphoneEnabled = presentation.getBoolean("iPhoneEnabled");
			final boolean podcastEnabled = presentation.getBoolean("podcastEnabled");
			final long totalViews = presentation.getLong("totalViews");
			final long totalVotes = presentation.getLong("totalVotes");
			final double totalVoteValue = presentation.getDouble("totalVoteValue");
			final long totalDownloads = presentation.getLong("totalDownloads");
			final double totalDuration = presentation.getDouble("totalDuration");
			
			presentationIds.add(presentationId);
			
			final ContentProviderOperation.Builder operation = ContentProviderOperation.newInsert(Channels.buildPresentationsDirUri(channelId));
			operation.withValue(Presentations.PRESENTATION_ID, presentationId)
				.withValue(Presentations.CREATED_ON, createdOn)
				.withValue(Presentations.MODIFIED_ON, modifiedOn)
				.withValue(Presentations.TITLE, title)
				.withValue(Presentations.SUMMARY, summary);
			if (thumbnailUrl != null && !isEmptyThumbnail(thumbnailUrl)) {
				operation.withValue(Presentations.THUMBNAIL_URL, thumbnailUrl);
			}
			if (mp3Url != null && !isEmptyThumbnail(mp3Url)) {
				operation.withValue(Presentations.MP3_URL, mp3Url);
			}
			operation.withValue(Presentations.VISIBLE_IPAD, visibleIpad)
				.withValue(Presentations.IPHONE_ENABLED, iphoneEnabled)
				.withValue(Presentations.PODCAST_ENABLED, podcastEnabled)
				.withValue(Presentations.TOTAL_VIEWS, totalViews)
				.withValue(Presentations.TOTAL_VOTES, totalVotes)
				.withValue(Presentations.TOTAL_VOTEVALUE, totalVoteValue)
				.withValue(Presentations.TOTAL_DOWNLOADS, totalDownloads)
				.withValue(Presentations.TOTAL_DURATION, totalDuration);
			batch.add(operation.build());
		}

//    	HashSet<Long> lostPresentationIds = getLostIds(presentationIds, Presentations.CONTENT_URI, PresentationsQuery.PROJECTION, PresentationsQuery.PRESENTATION_ID, resolver);
//    	for (Iterator<Long> it = lostPresentationIds(); it.hasNext(); ) {
//    		Long lostPresentationId = it.next();
//	    	Uri deleteUri = Presentations.buildPresentationUri(lostPresentationId.intValue());
//	    	batch.add(ContentProviderOperation.newDelete(deleteUri).build());
//    	}
		
		return batch;
	}

	@Override
	public void notify(ContentProviderResult[] result, ContentResolver resolver) throws JSONException {
		if (result != null && result.length > 0) {
			Log.d(TAG, "Notifying data set changes for " + result[0].uri);
			resolver.notifyChange(result[0].uri, null);
		}
	}

    private interface PresentationsQuery {
        String[] PROJECTION = {
                Presentations.PRESENTATION_ID,
        };

        int PRESENTATION_ID = 0;
    }

}
